﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Acl.DataCheck;

/// <summary>
/// 校验上下文对象
/// </summary>
public class ValidationContext
{
    /// <summary>
    /// 数据表集合
    /// </summary>
    public Acl.Dynamic.DynamicEntitySetCollection Tables { get; } = [];

    /// <summary>
    /// 约束集合
    /// </summary>
    public List<ConstraintItem> ConstraintItems { get; } = [];

    /// <summary>
    /// 日志对象
    /// </summary>
    public StringBuilder Logger => Current._errorMessage ?? (Current._errorMessage = new StringBuilder(512));

    /// <summary>
    /// 当前约束对象
    /// </summary>
    public ConstraintItem Current { get; internal set; }

    private Dictionary<int, List<dynamic>> _fkCodesCache = [];

    internal List<dynamic> GetFKCodes(string tableName, string columnName)
    {
        var key = HashCode.Combine(tableName, columnName);
        if (!_fkCodesCache.TryGetValue(key, out List<dynamic> result))
        {
            var table = Tables[tableName];

            result = [];

            foreach (var row in table)
            {
                result.Add(row[columnName]);
            }

            _fkCodesCache[key] = result;
        }

        return result;
    }

    /// <summary>
    /// 约束检查
    /// </summary>
    /// <param name="constraint"></param>
    public void Validate(ConstraintItem constraint)
    {
        Guard.NotNull(constraint, nameof(constraint));

        Current = constraint;

        if (!constraint.Enabled) return;

        var validator = ConstraintValidator.Create(constraint.Type);

        if (validator == null)
        {
            constraint.AppendLine($"暂时不支持：{constraint.Type} 的约束， 约束信息:{constraint}");
            constraint.Passed = false;
            return;
        }

        constraint.Passed = true;

        try
        {
            validator.Validate(this);
        }
        catch (Exception ex)
        {
            constraint.AppendLine($"{constraint.Type} 约束检查是吧，错误信息:{ex}， 约束信息:{constraint}");
            constraint.Passed = false;
        }
    }
}